Thread: int argc char *argv[]

  1. #1
    Unregistered
    Guest

    int argc char *argv[]

    Could someone explain the numerical codes returned when used on the command line. I am writing a program that expects an argument passed.

    C:>my_exe_name user_entered_filename

    If the user doesn't enter a filename then what return code is generated?

    if the user enters a filename that is not present what is the return code?

    if the user enters a filename that is invalid what is the return code?

    Can someone help?

  2. #2
    Unregistered
    Guest
    I'm sure there are good tutorials/web pages out there with info on this, but in short:

    argc is the number of command line arguments. If I remember correctly it will always have at least 1 as the value since the user has to enter the name of the exe to get it to run. So, your program has to check the value of argc to see if it is greater than 1... otherwise generate an error message and exit.

    As far as filenames, argv contains references to each command line string. The only way I know of to see if a file name is valid or present is to try and open the file using fopen or like function inside your program... something like

    in_file = fopen(<FILE NAME GOES HERE>,"r");
    if (in_file == (FILE *) NULL)
    {
    printf("Failed to open file.");
    exit(1);
    }

    There are probably other ways, but I don't know them.

  3. #3
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,380
    You are the one to decide what the return code is.

    int main (int argc, char **argv)

    The variable argc represents the number of arguments, which is at least 1. You can check the value and if there are too less or too much arguments, you can decide to return some errorcode.

    if (argc != 2)
    return ERRORCODE;

    The variable argv contains the arguments. The second argument on the command-line is the first one you normally use as parameter for your program. This can for example be the filename of the file to open. In case the file doesn't exist, you can return some errorcode.

    file = fopen (*++argv, "r");
    if (file == NULL)
    return ERRORCODE;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to combine these working parts??
    By transgalactic2 in forum C Programming
    Replies: 0
    Last Post: 02-01-2009, 08:19 AM
  2. I need help with variables, please
    By JOCAAN in forum C++ Programming
    Replies: 39
    Last Post: 12-08-2007, 04:16 PM
  3. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  4. getting a headache
    By sreetvert83 in forum C++ Programming
    Replies: 41
    Last Post: 09-30-2005, 05:20 AM
  5. Quack! It doesn't work! >.<
    By *Michelle* in forum C++ Programming
    Replies: 8
    Last Post: 03-02-2003, 12:26 AM